package com.ifast.common.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import com.ifast.common.domain.DictDO;

public class DicSet {
    private static DicSet ss = null;

    private static Map<String, List<Item>> dicmap = new HashMap<String, List<Item>>();

    public DicSet(List<DictDO> dicList, ServletContext application) {
        for (DictDO dic : dicList) {
            Item item = new Item(dic.getValue(), dic.getName());
            List<Item> list = dicmap.get(dic.getType());
            if (list != null && list.size() > 0) {
                list.add(item);
            } else {
                List<Item> tempList = new ArrayList<Item>();
                tempList.add(item);
                dicmap.put(dic.getType(), tempList);
            }
        }
        for (String key : dicmap.keySet()) {
            application.setAttribute(key + "_", dicmap.get(key));
            List<Item> list_ = new ArrayList<Item>();
            Item item = new Item("", "请选择");
            list_.add(item);
            list_.addAll(dicmap.get(key));
            application.setAttribute(key + "__", list_);
        }
    }

    public static List<Item> get(String type) {
        List<Item> list = dicmap.get(type);
        List<Item> tempList = new ArrayList<Item>();
        tempList.addAll(list);
        return tempList;
    }

    @SuppressWarnings("unchecked")
    public static Map<String,String> getMap(String type) {
        List<Item> list = dicmap.get(type);
        Map map = new LinkedHashMap();
        if (list != null && list.size() > 0) {
            for(Item item :list){
                map.put(item.getKey(), item.getValue());
            }
        }
        return map;
    }

    public static synchronized DicSet getInstanse(List<DictDO> dicList, ServletContext application) {
        if (ss == null)
            ss = new DicSet(dicList, application);
        return ss;
    }

    public static synchronized DicSet getInstanse2(List<DictDO> dicList, ServletContext application) {
        ss=null;
        dicmap = new HashMap<String, List<Item>>();
        ss = new DicSet(dicList, application);
        return ss;
    }
}
